package com.ruoyi.web.controller.pc.points;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.page.PageUtils;
import com.ruoyi.common.validator.group.AddGroup;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.domain.*;
import com.ruoyi.web.domain.vo.QueryVo;
import com.ruoyi.web.mapper.*;
import com.ruoyi.web.service.IPoiApplyService;
import com.ruoyi.web.service.IPoiManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/points/poiManagement")
public class PoiManagementController extends BaseController {

    @Autowired
    private IPoiManagementService poiManagementService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private PoiApplyMapper poiApplyMapper;

    @Autowired
    private UcQuoTableMapper ucQuoTableMapper;

    @Autowired
    private PoiApplyItemMapper poiApplyItemMapper;

    @Autowired
    private PoiApplyImageMapper poiApplyImageMapper;


    @PreAuthorize("@ss.hasPermi('points:poiManagement:list')")
    @GetMapping("/list")
    public TableDataInfo list(QueryVo queryVo) {
        SysUser sysUser = new SysUser();
        sysUser.setNickName(queryVo.getQKey());
        if(queryVo.getQIds1()!=null && !StringUtils.isEmpty(queryVo.getQIds1())){
            sysUser.setDeptId(queryVo.getQIds1().get(queryVo.getQIds1().size()-1));
        }
        sysUser.setStatus("0");
        startPage();
        List<SysUser> list = sysUserService.selectUserList(sysUser);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('points:poiManagement:add')")
    @Log(title = "评分", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody PoiApply poiApply){
        poiManagementService.insert(poiApply);
        return toAjax(1);
    }

    @GetMapping("/haveData")
    public AjaxResult haveData(PoiApply poiApply) {
        QueryWrapper<PoiApply> qwPoiApply = new QueryWrapper<>();
        qwPoiApply.eq("user_id",poiApply.getUserId());
        qwPoiApply.eq("year",poiApply.getYear());
        List<PoiApply> poiApplies = poiApplyMapper.selectList(qwPoiApply);
        Set<Integer> quarterList = poiApplies.stream().map(PoiApply::getQuarter).distinct().collect(Collectors.toSet());
        return success(quarterList);
    }

    @RequestMapping("/searchApplyByUser/{userId}")
    public AjaxResult searchApplyByUser(@PathVariable("userId") Long userId){

        Date date =new Date();

        QueryWrapper<PoiApply> qwPoiApply = new QueryWrapper<>();
        qwPoiApply.eq("user_id",userId);
        qwPoiApply.eq("year",DateUtils.getYear(date));
        qwPoiApply.eq("quarter",DateUtils.getQuarter(date));
        qwPoiApply.eq("quota_from",20);
        PoiApply poiApply = poiApplyMapper.selectOne(qwPoiApply);

        if(poiApply != null && poiApply.getId() != null && poiApply.getId() != 0L){

            QueryVo queryVo = new QueryVo();
            queryVo.setQId(poiApply.getId());
            poiApply = poiApplyMapper.selectByApply(queryVo);

            queryVo = new QueryVo();
            queryVo.setQId(poiApply.getTableId());
            queryVo.setQFrom(20);
            UcQuoTable ucQuoTable = ucQuoTableMapper.searchBayId(queryVo);
            poiApply.setUcQuoProjects(ucQuoTable.getUcQuoProjectList());

            /*Map<Long,PoiApplyItem> poiApplyItemMap = new HashMap<>();
            for (PoiApplyItem poiApplyItem : poiApply.getPoiApplyItemList()) {
                poiApplyItemMap.put(poiApplyItem.getItemId(),poiApplyItem);
            }
            poiApply.setPoiApplyItemMap(poiApplyItemMap);*/

            for (UcQuoProject ucQuoProject : poiApply.getUcQuoProjects()) {
                for (UcQuoProjectItem ucQuoProjectItem : ucQuoProject.getUcQuoProjectItems()) {

                    Integer numCanApply = 999;
                    LambdaQueryWrapper<PoiApplyItem> lqwPoiApplyItem = new LambdaQueryWrapper<>();
                    lqwPoiApplyItem.eq(PoiApplyItem::getItemId,ucQuoProjectItem.getId());
                    lqwPoiApplyItem.eq(PoiApplyItem::getUserId,userId);
                    if(ucQuoProjectItem.getLimitType() >=20){
                        numCanApply = ucQuoProjectItem.getLimitMax();
                        lqwPoiApplyItem.eq(PoiApplyItem::getYear,poiApply.getYear());
                    }
                    if(ucQuoProjectItem.getLimitType() >=30){
                        lqwPoiApplyItem.eq(PoiApplyItem::getQuarter,poiApply.getQuarter());
                    }
                    if(ucQuoProjectItem.getLimitType() >=40){
                        lqwPoiApplyItem.eq(PoiApplyItem::getMonth,poiApply.getMonth());
                    }
                    int numApply = poiApplyItemMapper.selectList(lqwPoiApplyItem).stream().mapToInt(PoiApplyItem::getNum).sum();

                    PoiApplyItem poiApplyItem = poiApply.getPoiApplyItemList().stream().filter(item -> {
                        return item.getItemId().equals(ucQuoProjectItem.getId());
                    }).findFirst().orElse(null);

                    if(poiApplyItem!=null){
                        ucQuoProjectItem.setNum(poiApplyItem.getNum());
                        ucQuoProjectItem.setScoreText(poiApplyItem.getScore());
                        ucQuoProjectItem.setContent(poiApplyItem.getContent());
                        ucQuoProjectItem.setNumCanApply(numCanApply - numApply + ucQuoProjectItem.getNum());
                    }else{
                        ucQuoProjectItem.setNumCanApply(numCanApply - numApply);
                    }

                }
            }


            QueryWrapper<PoiApplyImage> qwPoiApplyImage=new QueryWrapper<>();
            qwPoiApplyImage.eq("apply_id",poiApply.getId());
            List<PoiApplyImage> poiApplyImageList = poiApplyImageMapper.selectList(qwPoiApplyImage);

            if(!StringUtils.isEmpty(poiApplyImageList)){
                poiApply.setImgList(new ArrayList<>());
                for (PoiApplyImage poiApplyImage : poiApplyImageList) {
                    poiApply.getImgList().add(poiApplyImage.getImage());
                }
            }

        }else{

            poiApply = new PoiApply();
            poiApply.setTimeStart(date);
            poiApply.setYear(DateUtils.getYear(date));
            poiApply.setQuarter(DateUtils.getQuarter(date));
            poiApply.setMonth(DateUtils.getMonth(date));

            QueryWrapper<UcQuoTable> qwUcQuoTable = new QueryWrapper<>();
            qwUcQuoTable.eq("is_used",1);
            UcQuoTable ucQuoTableTemp = ucQuoTableMapper.selectOne(qwUcQuoTable);
            QueryVo queryVo = new QueryVo();
            queryVo.setQId(ucQuoTableTemp.getId());
            queryVo.setQFrom(20);
            UcQuoTable ucQuoTable = ucQuoTableMapper.searchBayId(queryVo);
            poiApply.setTableId(ucQuoTable.getId());
            poiApply.setTableName(ucQuoTable.getName());
            poiApply.setUcQuoProjects(ucQuoTable.getUcQuoProjectList());


            for (UcQuoProject ucQuoProject : poiApply.getUcQuoProjects()) {
                for (UcQuoProjectItem ucQuoProjectItem : ucQuoProject.getUcQuoProjectItems()) {

                    Integer numCanApply = 999;
                    LambdaQueryWrapper<PoiApplyItem> lqwPoiApplyItem = new LambdaQueryWrapper<>();
                    lqwPoiApplyItem.eq(PoiApplyItem::getItemId,ucQuoProjectItem.getId());
                    lqwPoiApplyItem.eq(PoiApplyItem::getUserId,userId);
                    if(ucQuoProjectItem.getLimitType() >=20){
                        numCanApply = ucQuoProjectItem.getLimitMax();
                        lqwPoiApplyItem.eq(PoiApplyItem::getYear,poiApply.getYear());
                    }
                    if(ucQuoProjectItem.getLimitType() >=30){
                        lqwPoiApplyItem.eq(PoiApplyItem::getQuarter,poiApply.getQuarter());
                    }
                    if(ucQuoProjectItem.getLimitType() >=40){
                        lqwPoiApplyItem.eq(PoiApplyItem::getMonth,poiApply.getMonth());
                    }
                    int numApply = poiApplyItemMapper.selectList(lqwPoiApplyItem).stream().mapToInt(PoiApplyItem::getNum).sum();

                    ucQuoProjectItem.setNumCanApply(numCanApply - numApply);

                }
            }

        }


        return success(poiApply);
    }


    @PreAuthorize("@ss.hasPermi('points:poiManagement:export')")
    @Log(title = "积分管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@RequestBody QueryVo queryVo, HttpServletResponse response) throws Exception {

        PoiApply poiApply = poiApplyMapper.selectByApply1(queryVo);

        if(poiApply!=null){
            queryVo = new QueryVo();
            queryVo.setQId(poiApply.getTableId());
            UcQuoTable ucQuoTable = ucQuoTableMapper.searchBayId(queryVo);
            poiApply.setUcQuoProjects(ucQuoTable.getUcQuoProjectList());

            for (UcQuoProject ucQuoProject : poiApply.getUcQuoProjects()) {

                double score = poiApply.getPoiApplyItemList().stream().filter(item -> {
                    return item.getProjectId().equals(ucQuoProject.getId());
                }).mapToDouble(PoiApplyItem::getScore).sum();
                double score1 = poiApply.getPoiApplyItemList().stream().filter(item -> {
                    return item.getProjectId().equals(ucQuoProject.getId());
                }).mapToDouble(item -> Optional.ofNullable(item.getScore1()).orElse(0.0)).sum();
                double score2 = poiApply.getPoiApplyItemList().stream().filter(item -> {
                    return item.getProjectId().equals(ucQuoProject.getId());
                }).mapToDouble(item -> Optional.ofNullable(item.getScore2()).orElse(0.0)).sum();
                ucQuoProject.setScore(score);
                ucQuoProject.setScore1(score1);
                ucQuoProject.setScore2(score2);

                for (UcQuoProjectItem ucQuoProjectItem : ucQuoProject.getUcQuoProjectItems()) {
                    PoiApplyItem poiApplyItem = poiApply.getPoiApplyItemList().stream().filter(item -> {
                        return item.getItemId().equals(ucQuoProjectItem.getId());
                    }).findFirst().orElse(null);

                    if(poiApplyItem!=null){
                        ucQuoProjectItem.setNum(poiApplyItem.getNum());
                        ucQuoProjectItem.setScoreText(poiApplyItem.getScore());
                        ucQuoProjectItem.setContent(poiApplyItem.getContent());
                        ucQuoProjectItem.setNum1(poiApplyItem.getNum1());
                        ucQuoProjectItem.setNum2(poiApplyItem.getNum2());
                        ucQuoProjectItem.setScoreText1(poiApplyItem.getScore1());
                        ucQuoProjectItem.setScoreText2(poiApplyItem.getScore2());
                    }
                }

            }


            List<PoiApplyImage> poiApplyImageList = poiApply.getPoiApplyImages();
            if(!StringUtils.isEmpty(poiApplyImageList)){
                poiApply.setImgList(new ArrayList<>());
                for (PoiApplyImage poiApplyImage : poiApplyImageList) {
                    poiApply.getImgList().add(poiApplyImage.getImage());
                }
            }


            poiManagementService.export(poiApply,response);


        }






    }
}

